﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MyPublish.Connection
{
    public class DataConnectionString
    {
        public const string PROVIDER_KEY = "provider";
        public const string USERNAME_KEY = "username";
        public const string PASSWORD_KEY = "password";

        private Dictionary<string, string> KeyValues { get; set; }

        public DataConnectionString()
        {
            this.KeyValues = new Dictionary<string, string>()
            {
                {PROVIDER_KEY,string.Empty},
                {USERNAME_KEY,string.Empty},
                {PASSWORD_KEY,string.Empty},
            };
        }

        public string Provider 
        { 
            get { return KeyValues[PROVIDER_KEY]; } 
            set { KeyValues[PROVIDER_KEY] = value; } 
        }
        public string UserName
        {
            get { return KeyValues[USERNAME_KEY]; }
            set { KeyValues[USERNAME_KEY] = value; }
        }
        public string Password
        {
            get { return KeyValues[PASSWORD_KEY]; }
            set { KeyValues[PASSWORD_KEY] = value; }
        }

        public override string ToString()
        {
            StringBuilder sb = new StringBuilder();
            foreach (KeyValuePair<string, string> keyValue in KeyValues)
            {
                sb.AppendFormat("{0}={1};", keyValue.Key, keyValue.Value);
            }
            return sb.ToString().TrimEnd(new char[] {';' });
        }

        public static DataConnectionString Parse(string connString)
        {
            connString = connString.Trim(new char[]{';'});
            DataConnectionString conn = new DataConnectionString();

            string[] splits = connString.Split(new char[] { ';' });
            foreach (string split in splits)
            {
                if (split.Equals(PROVIDER_KEY, StringComparison.InvariantCultureIgnoreCase))
                {
                    conn.KeyValues[PROVIDER_KEY] = split;
                }
                if (split.Equals(USERNAME_KEY, StringComparison.InvariantCultureIgnoreCase))
                {
                    conn.KeyValues[USERNAME_KEY] = split;
                }
                if (split.Equals(PASSWORD_KEY, StringComparison.InvariantCultureIgnoreCase))
                {
                    conn.KeyValues[PASSWORD_KEY] = split;
                }
            }

            return conn;
        }
    }
}
